package uk.co.kevinlockwood.kol.droid.services;

import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import uk.co.kevinlockwood.kol.droid.DroidHelpers;
import uk.co.kevinlockwood.kol.droid.G;
import uk.co.kevinlockwood.kol.messages.KoLMessage;
import uk.co.kevinlockwood.kol.messages.KoLMessageServiceBinder;
import uk.co.kevinlockwood.kol.pages.LoggedOutPage;
import uk.co.kevinlockwood.kol.pages.LogoutPage;
import uk.co.kevinlockwood.kol.pages.NewChatMessages;
import uk.co.kevinlockwood.kol.pages.KoLPageBuilder;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.IBinder;

public class KoLMessageService extends Service {
	private String sessionid;
	private Timer timer;
	private KoLMessageServiceBinder binder;
	private Boolean started;
	private long period = 2000;
	private SharedPreferences settings;
	private KoLPageBuilder builder;

	@Override
	public void onCreate() {
		DroidHelpers.trace("KoLMessageService.onCreate()");
		settings = getSharedPreferences(G.PREFS_NAME, MODE_PRIVATE);
		timer = new Timer();
		binder = new KoLMessageServiceBinder();
		started = Boolean.FALSE;
		super.onCreate();
	}

	@Override
	public void onDestroy() {
		DroidHelpers.trace("KoLMessageService.onDestroy()");
		try {
			// stop any timers, threads, etc
			timer.cancel();

			// log out
			DroidHelpers.debug("totally logging out session id [",sessionid,"]");
			builder.buildPage(new LogoutPage());
			builder.buildPage(new LoggedOutPage());
		} catch (Exception e) {
			// well it's no good passing it up the chain here
			DroidHelpers.printStackTrace(e);
		} finally {
			super.onDestroy();
		}
	}

	@Override
	public void onLowMemory() {
		DroidHelpers.trace("KoLMessageService.onLowMemory()");
		// sweeeet
		super.onLowMemory();
	}

	private class MessageTask extends TimerTask {
		KoLMessageService parent;
		String lastrun;
		SharedPreferences settings;
		Editor editor;
		public MessageTask(KoLMessageService serv) {
			parent = serv;
			lastrun = "0";
			settings = parent.settings;
			editor = settings.edit();
		}
		@Override
		public void run() {
			if (settings.getString(G.SESSION_ID, null) == null) {
				parent.stopSelf();
			} else {
				long t = new Date().getTime();
				NewChatMessages ch = builder.buildPage(new NewChatMessages(lastrun));
				lastrun = ch.getLastCheck();
				editor.putLong(G.LAST_UPDATE, t);
				editor.commit();
				parent.takeMessages(ch.getMesssages());
			}
		}
	}

	private void takeMessages(List<KoLMessage> msgs) {
		for (KoLMessage msg : msgs) {
			DroidHelpers.trace(msg.toString());
			binder.addMessage(msg);
		}
	}

	private void startUpService() {
		if (sessionid == null) {
			sessionid = settings.getString(G.SESSION_ID, null);
			builder = new KoLPageBuilder(this, sessionid);
			DroidHelpers.debug("found session key: ",sessionid);
		}
		if (Boolean.FALSE == started && sessionid != null) {
			DroidHelpers.trace("starting message service task");
			timer.schedule(new MessageTask(this), 0, period);
			started = Boolean.TRUE;
		}
	}

	@Override
	public boolean onUnbind(Intent intent) {
		DroidHelpers.trace("KoLMessageService.onUnbind()");
		return super.onUnbind(intent);
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		DroidHelpers.trace("ChatService onStartCommand");
		startUpService();
		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public IBinder onBind(Intent intent) {
		DroidHelpers.trace("ChatService onBind");
		startUpService();
		return binder;
	}
}
